#!/bin/bash

# SPDX-FileCopyrightText: © 2018 Siemens AG
# Author: Gaurav Mishra <mishra.gaurav@siemens.com>

# SPDX-License-Identifier: GPL-2.0-only
#
# This script helps you install build and runtime dependencies on a system.
# It is NOT indented to replace package dependencies, it's just a tool to
# make testing the "upstream" build and install process. If you determine
# this script isn't installing something you think it should, consult
# the packaging metadata for the system in question as that is the
# canonical location for such info, then fix it there first and also
# update this file and the INSTALL document.

show_help() {
  cat <<EOF
Usage: prepare-test [options]
  -a              : Accept the warning prompt
  -f              : Create fossy user in Database
  -t              : Create fossologytest user in Database
  -y              : Automatic yes to prompts
  -u              : Super user for connection (default postgres)
  -p              : Password for super user (default none)
  -h              : This help text
EOF
}


# figure out what distro we're on
DISTRO=$(lsb_release --id --short)

#
# Don't show the -y option.  Should only be used for install testing, as using
# it without being careful can destroy your system.
#
YesOpt=''

# Setting default options
CreateFossy="N"
CreateFossyTest="N"
PG_USER="postgres"
PG_PASS=""

# Use localhost as default host
if [[ -z "${PGHOST}" ]]; then
  PGHOST="localhost"
fi

cat <<EOF
****************************************************************************
* Please note, the script changes the owner of /var/local/cache/fossology! *
* Also creates a test repo under /srv/fossologyTestRepo.                   *
* Creates a PostgreSQL user fossy and fossologytest and stores password    *
* under ~/.pgpass                                                          *
****************************************************************************
* NOTE: Above changes may break your current installation!!                *
* NOTE: Please do not run on a productive instance!!                       *
****************************************************************************

EOF

while getopts ":aftyhu:p:" o; do
  case "${o}" in
    a)
      WarnAccept="Y"
      ;;
    f)
      CreateFossy="Y"
      ;;
    t)
      CreateFossyTest="Y"
      ;;
    y)
      YesOpt='-y'
      ;;
    u)
      PG_USER="${OPTARG}"
      ;;
    p)
      PG_PASS="${OPTARG}"
      ;;
    h)
      show_help; exit;;
    *)
      show_help; exit 1;;
   esac
done

if [[ -z ${WarnAccept} ]]; then
  read -r -n 1 -p "Are you sure run this script?(y/N) " WarnAccept
  if [[ -z ${WarnAccept} ]]; then
    WarnAccept="N"
  fi
fi

echo

if echo ${WarnAccept} | grep -q -e "^[yY]$" ; then
  uid=$(id -u)
  gid=$(id -g)
  sudo mkdir -p /var/local/cache/fossology
  sudo chown "${uid}:${gid}" /var/local/cache/fossology
  sudo mkdir -p /srv/fossologyTestRepo
  sudo chown "${uid}:${gid}" /srv/fossologyTestRepo
  if [[ -z "${PG_PASS}" ]]; then
    sudo --preserve-env su --whitelist-environment="PGHOST" postgres -c "echo 'CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";'|psql -d template1" || true
  else
    echo 'CREATE EXTENSION IF NOT EXISTS "uuid-ossp";'|PGPASSWORD="${PG_PASS}" psql -d template1 -U ${PG_USER} || true
  fi
  if [[ "${CreateFossy}" == "Y" ]]; then
    if [[ -z "${PG_PASS}" ]]; then
      sudo --preserve-env su --whitelist-environment="PGHOST" postgres -c "echo \"CREATE USER fossy WITH PASSWORD 'fossy' CREATEDB;\"|psql" || true >/dev/null
      sudo --preserve-env su --whitelist-environment="PGHOST" postgres -c "echo 'CREATE DATABASE fossology; GRANT ALL PRIVILEGES ON DATABASE fossology TO fossy;'|psql" || true
    else
      echo "CREATE USER fossy WITH PASSWORD 'fossy' CREATEDB;"|PGPASSWORD="${PG_PASS}" psql -U ${PG_USER} || true >/dev/null
      echo 'CREATE DATABASE fossology; GRANT ALL PRIVILEGES ON DATABASE fossology TO fossy;'|PGPASSWORD="${PG_PASS}" psql -U ${PG_USER} || true
    fi
    echo "${PGHOST}:*:*:fossy:fossy" >> ~/.pgpass
    chmod 0600 ~/.pgpass
  fi
  if [[ "${CreateFossyTest}" == "Y" ]]; then
    testDbPassword=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 13)
    if [[ -z "${PG_PASS}" ]]; then
      sudo --preserve-env su --whitelist-environment="PGHOST" postgres -c "echo \"CREATE USER fossologytest WITH CREATEDB LOGIN PASSWORD '${testDbPassword}';\"|psql" || true >/dev/null
    else
      echo "CREATE USER fossologytest WITH CREATEDB LOGIN PASSWORD '${testDbPassword}';"|PGPASSWORD="${PG_PASS}" psql -U ${PG_USER} || true >/dev/null
    fi
    echo "${PGHOST}:*:*:fossologytest:${testDbPassword}" >> ~/.pgpass
    chmod 0600 ~/.pgpass
  fi
  case "${DISTRO}" in
    Debian|Ubuntu|LinuxMint)
      if dpkg-query --show --showformat='${db:Status-Status}' cppcheck | grep -q 'not-installed' ; then
        sudo apt-get install -q $YesOpt cppcheck
      else
        echo "cppcheck installed. Not installing again."
      fi ;;
    Fedora|RedHatEnterprise*|CentOS)
      yum $YesOpt install cppcheck ;;
  esac
fi
